package com.tchepannou.limbe.dao;

import com.tchepannou.limbe.model.Model;

import java.util.HashMap;
import java.util.Map;

public class DaoFactory
{
    //-- StaticAttributes
    private static final Map<Class<?>, Dao> MAPPING;
    static{
        MAPPING = new HashMap<Class<?>, Dao>();
    }

    //-- DaoFactory overrides
    public static Dao get(Class<?> type)
    {
        Dao dao = MAPPING.get(type);
        if (dao == null)
        {
            String classname = null;
            if (Model.class.isAssignableFrom(type))
            {
                String pkg = type.getPackage().getName();
                classname = pkg.replaceAll("domain", "dao") + "." + type.getSimpleName() + "Dao";
            }

            if (classname != null)
            {
                synchronized (MAPPING)
                {
                    try
                    {
                        Class<? extends Dao> clazz = (Class<? extends Dao>)Class.forName(classname);
                        dao = clazz.newInstance();

                        MAPPING.put(type, dao);
                    }
                    catch (ClassNotFoundException e)
                    {
                        throw new IllegalStateException("Bad DAO for " + type + ": " + classname, e);
                    }
                    catch (InstantiationException e)
                    {
                        throw new IllegalStateException("Unable to instantiate: " + classname, e);
                    }
                    catch (IllegalAccessException e)
                    {
                        throw new IllegalStateException("Unable to instantiate: " + classname, e);
                    }
                }
            }
        }

        return dao;
    }
}
